// Background script for SVG Viewer extension
chrome.runtime.onInstalled.addListener(() => {
    console.log('SVG Viewer extension installed successfully');
});

// Initialize default settings if needed
chrome.runtime.onInstalled.addListener(() => {
    chrome.storage.local.get(['svgCode'], function(result) {
        if (!result.svgCode) {
            // Set default example SVG if no previous SVG code exists
            const defaultSvg = `<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <!-- 背景圆形 -->
  <circle cx="100" cy="100" r="90" fill="#2196F3"/>
  
  <!-- 眼睛形状 -->
  <path d="M100 60 C40 60, 40 140, 100 140 C160 140, 160 60, 100 60" 
        fill="white" stroke="#1565C0" stroke-width="4"/>
  
  <!-- 瞳孔 -->
  <circle cx="100" cy="100" r="20" fill="#1565C0"/>
  
  <!-- SVG 文字 -->
  <text x="100" y="185" 
        font-family="Arial" 
        font-size="28" 
        fill="red" 
        text-anchor="middle">
    SVG
  </text>
</svg>
`;

            chrome.storage.local.set({ svgCode: defaultSvg });
        }
    });
});

// 添加浏览器按钮点击事件处理
chrome.action.onClicked.addListener(function(tab) {
    console.log('Extension icon clicked');

    try {
        // 检查是否已有打开的 SVG 编辑器标签页
        chrome.tabs.query({}, function(tabs) {
            if (chrome.runtime.lastError) {
                console.error('Error querying tabs:', chrome.runtime.lastError);
                return;
            }

            let found = false;
            let tabId = null;

            // 遍历所有标签页
            for (let i = 0; i < tabs.length; i++) {
                if (tabs[i].url && tabs[i].url.includes('index.html')) {
                    found = true;
                    tabId = tabs[i].id;
                    break;
                }
            }

            if (found && tabId) {
                console.log('Found existing tab, activating:', tabId);
                // 激活已存在的标签页
                chrome.tabs.update(tabId, { active: true }, function() {
                    if (chrome.runtime.lastError) {
                        console.error('Error activating tab:', chrome.runtime.lastError);
                    }
                });
            } else {
                console.log('Creating new tab');
                // 在新标签页中打开编辑器
                chrome.tabs.create({
                    url: chrome.runtime.getURL('index.html')
                }, function(tab) {
                    if (chrome.runtime.lastError) {
                        console.error('Error creating tab:', chrome.runtime.lastError);
                    } else {
                        console.log('New tab created:', tab.id);
                    }
                });
            }
        });
    } catch (error) {
        console.error('Error in click handler:', error);
    }
});